package com.net.xpay.admin.controller.admin;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.common.model.ResultData;
import com.net.common.model.ResultPagedList;
import com.net.xpay.admin.po.CloseUserWithdrawPo;
import com.net.xpay.admin.po.ConfirmOfflineUserWithdrawPo;
import com.net.xpay.common.annotation.OperateLog;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.domain.sync.CommonUserWithdrawRecord;
import com.net.xpay.common.enums.config.FunctionModule;
import com.net.xpay.common.enums.config.MethodType;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.common.manager.sync.CommonUserWithdrawRecordManager;
import com.net.xpay.common.model.search.CommonUserWithdrawSearchModel;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.enums.UserWithdrawStatus;
import com.net.xpay.core.service.UserWithdrawService;
import com.net.shard.ShardUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 86188
 */
@RestController
@RequestMapping("/admin/user-withdraw-record")
@Api(tags = "运营/用户提现", description = "运营 用户提现 net")
public class AdminUserWithdrawController {

    @Autowired
    private CommonUserWithdrawRecordManager commonUserWithdrawRecordManager;

    @Autowired
    private UserWithdrawService userWithdrawService;

    @Autowired
    private UserShardManager userShardManager;

    /**
     * 搜索
     */
    @ApiOperation("搜索")
    @PostMapping("/search")
    @PreAuthorize("hasAnyRole('ADMIN', 'user-withdraw-record::search')")
    public ResultPagedList<CommonUserWithdrawRecord> searchUserWithdrawRecord(@RequestBody CommonUserWithdrawSearchModel searchModel) {
        Preconditions.checkArgument(searchModel != null);

        List<CommonUserWithdrawRecord> records = commonUserWithdrawRecordManager.search(searchModel);
        long count = commonUserWithdrawRecordManager.searchCount(searchModel);

        //成功提现金额
        long amount = commonUserWithdrawRecordManager.sumSuccessTransferMoney(searchModel.getUserId(),searchModel.getMinEndTime(),searchModel.getMaxEndTime());
        ResultPagedList<CommonUserWithdrawRecord> ret = new ResultPagedList<>(records, count, searchModel);
        ret.setExtra(new BigDecimal(amount).multiply(new BigDecimal("0.01")).setScale(2, RoundingMode.HALF_UP).toString());
        return ret;
    }

    @ApiOperation("转账")
    @PostMapping("/trans")
    @PreAuthorize("hasAnyRole('ADMIN', 'user-withdraw-record::trans')")
    @OperateLog(methodType = MethodType.INSERT, methodDesc = "商户提现线上转账",module = FunctionModule.MERCHANT_WITHDRAW)
    public ResultData<String> transMoney(Long id) {
        Preconditions.checkArgument(id != null);
        //打款支付宝和打款手机号
        String payUrl = userWithdrawService.transUserWithdrawRecord(id);

        return new ResultData<>(payUrl);
    }

    @ApiOperation("关闭")
    @PostMapping("/close")
    @PreAuthorize("hasAnyRole('ADMIN', 'user-withdraw-record::close')")
    @OperateLog(methodType = MethodType.UPDATE, methodDesc = "取消商户提现",module = FunctionModule.MERCHANT_WITHDRAW)
    public ResultData<Boolean> closeUserWithdraw(@RequestBody CloseUserWithdrawPo po) {
        Preconditions.checkArgument(po.getId() != null);

        CommonUserWithdrawRecord record = commonUserWithdrawRecordManager.getById(po.getId());
        if (record.getPayStatus() != UserWithdrawStatus.WAIT_PAY) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "待转账状态才可以关闭");
        }

        UserShard shard = userShardManager.getById(record.getUserId());
        try {
            ShardUtil.setShardContext(shard.getShardId());
            userWithdrawService.closeUserWithdraw(po.getId(), po.getRemark());
        } finally {
            ShardUtil.cleanShardContext();
        }



        return new ResultData<>(true);
    }

    @ApiOperation("确认转账")
    @PostMapping("/confirm")
    @PreAuthorize("hasAnyRole('ADMIN', 'user-withdraw-record::confirm')")
    @OperateLog(methodType = MethodType.UPDATE, methodDesc = "确认线下转账",module = FunctionModule.MERCHANT_WITHDRAW)
    public ResultData<Boolean> confirmUserWithdraw(@RequestBody ConfirmOfflineUserWithdrawPo po) {
        Preconditions.checkArgument(po.getId() != null);
        if (Strings.isNullOrEmpty(po.getRemark())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请填写备注");
        }

        CommonUserWithdrawRecord record = commonUserWithdrawRecordManager.getById(po.getId());
        if (record.getPayStatus() != UserWithdrawStatus.WAIT_PAY) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "待转账状态才可以确认转账");
        }

        UserShard shard = userShardManager.getById(record.getUserId());
        try {
            ShardUtil.setShardContext(shard.getShardId());
            userWithdrawService.confirmOfflineUserWithdraw(po.getId(), po.getRemark());
        } finally {
            ShardUtil.cleanShardContext();
        }



        return new ResultData<>(true);
    }

}
